package com.lin.manager.file.service.impl;

import com.lin.manager.common.ex.BizException;
import com.lin.manager.file.oss.OssService;
import com.lin.manager.file.entity.FileConfigEntity;
import com.lin.manager.file.model.vo.FileVo;
import com.lin.manager.file.service.FileConfigService;
import com.lin.manager.file.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @作者: 林江
 * @创建时间: 2024/3/22
 * @功能:
 */
@Service
public class FileServiceImpl implements FileService {
    @Autowired
    FileConfigService fileConfigService;
    OssService ossService;

    /**
     * 文件上传
     * 1.本地上传
     * 2.云服务上传
     *
     * @param file
     */
    @Override
    public Map upload(MultipartFile file) throws Exception {
        // 获取启用中的配置参数
        List<FileConfigEntity> fileConfigs = fileConfigService.listByEnable();
        if (fileConfigs.size() != 0) {
            Map<String, Object> map = new HashMap<>();
            for (FileConfigEntity fileConfigEntity : fileConfigs) {
                // 上传
                ossService.doUpload(file, fileConfigEntity, map);
            }
            if (map.isEmpty()) {
                throw new BizException("上传文件失败");
            }
            return map;
        }
        throw new BizException("没有可选的文件上传参数，请到文件管理中配置");
    }

    @Override
    public void download(FileVo vo, String code, HttpServletResponse response) throws Exception {
        FileConfigEntity fileConfig = fileConfigService.getByFileConfigKey(code + ":1");
        if (fileConfig != null) {
            ossService.doDownload(response, vo, fileConfig);
        } else {
            throw new BizException("文件配置编码【" + code + "】错误，请重试");
        }
    }
}
